/*********************************************************************************
 * Copyright (c) 2006 Forschungszentrum Juelich GmbH 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * (1) Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer at the end. Redistributions in
 * binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or other
 * materials provided with the distribution.
 * 
 * (2) Neither the name of Forschungszentrum Juelich GmbH nor the names of its 
 * contributors may be used to endorse or promote products derived from this 
 * software without specific prior written permission.
 * 
 * DISCLAIMER
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 ********************************************************************************/
package pl.umk.mat.fred.unicore.urc.storagemanagement.views.cellEditors;

import java.util.Random;

import org.apache.commons.httpclient.util.URIUtil;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;

import pl.umk.mat.fred.unicore.urc.storagemanagement.dialogs.ServiceSelectionDialog;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tools.StorageTools;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.CatalogNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.GridNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.MultiplyCatalogNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.StorageNode;

import com.intel.gpe.clients.impl.transfers.U6ProtocolConstants;
import com.intel.gpe.gridbeans.parameters.IFileParameterValue;

import de.fzj.unicore.rcp.gpe4eclipse.GPEActivator;

/**
 * @author demuth
 * 
 */
public class StageOutTypeU6StorageCellEditor extends DialogCellEditor {

	private class SelectionValidator implements ISelectionStatusValidator {
		
		public IStatus validate(Object[] selection) {
			if ((selection != null) && selection.length > 0) {
				if ((selection[0] instanceof StorageNode) ||
					(selection[0] instanceof CatalogNode) ||
					(selection[0] instanceof MultiplyCatalogNode)) {
					return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, IStatus.OK, "",
							null);
				} else if (selection[0] instanceof GridNode) {
					GridNode gridNode = (GridNode) selection[0];
					if (!gridNode.getRootNode().areStoragesVisible()) {
						return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, IStatus.OK, "",
								null);
					}
				}
			}
			return new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.ERROR,
					"No storage or directory selected.", null);
		}
	}
	
	protected IFileParameterValue file;

	/**
	 * The label that gets reused by <code>updateLabel</code>.
	 */
	private Label defaultLabel;

	/** A CellEditor, opening a FileBrowser for selecting a File */
	public StageOutTypeU6StorageCellEditor(Composite parent) {
		super(parent);
	}

	@Override
	protected Control createContents(Composite cell) {
		defaultLabel = new Label(cell, SWT.LEFT);
		defaultLabel.setFont(cell.getFont());
		defaultLabel.setBackground(cell.getBackground());
		return defaultLabel;
	}

	@Override
	protected void doSetValue(Object value) {
		IFileParameterValue file = (IFileParameterValue) value;
		super.doSetValue(value);
		updateContents(file.getSource().getInternalString());
	}

	@Override
	protected Object openDialogBox(Control cellEditorWindow) {
		ServiceSelectionDialog serviceSelectionDialog = new ServiceSelectionDialog();
		try {
			file = (IFileParameterValue) this.getValue();
			IFileParameterValue result;
			try {
				result = file.clone();
			} catch (Exception e) {
				result = file;
			}
			serviceSelectionDialog.setTitle("Please select a file.");
			serviceSelectionDialog.setValidator(new SelectionValidator());
			serviceSelectionDialog.open();

			Object o = serviceSelectionDialog.getFirstResult();
			String relative = result.getSource().getRelativePath();
			relative = URIUtil.encode(relative,
					org.apache.commons.httpclient.URI.allowed_fragment);
			String parentDir = null;
			String displayed = null;
			if (o instanceof GridNode) {
				GridNode gridNode = (GridNode) o;
				StorageNode storageNode = StorageTools.randomStorageNode(gridNode);
				parentDir = storageNode.getStorage().getUrl();
				if (!parentDir.endsWith("#")) {
					parentDir += "#";
				}
				displayed = storageNode.getStorage().getName() + "/" + relative;
			} else if (o instanceof StorageNode) {
				StorageNode storageNode = (StorageNode) o;
				parentDir = storageNode.getStorage().getUrl();
				if (!parentDir.endsWith("#")) {
					parentDir += "#";
				}
				displayed = storageNode.getStorage().getName() + "/" + relative;
			} else if (o instanceof MultiplyCatalogNode) {
				MultiplyCatalogNode multiCatalogNode = (MultiplyCatalogNode) o;
				CatalogNode catalogNode = StorageTools.randomCatalogNode(multiCatalogNode);
				if (catalogNode == null) {
					return null;
				}
				String storageURL = catalogNode.getStorage().getUrl();
				if (!storageURL.endsWith("#")) {
					storageURL += "#";
				}
				parentDir = storageURL + catalogNode.getPath();
				if (!parentDir.endsWith("/")) {
					parentDir += "/";
				}
				
				String fileNodePath = URIUtil.encode(catalogNode.getPath(),
							org.apache.commons.httpclient.URI.allowed_fragment);
				displayed = catalogNode.getStorage().getName() + "/" + fileNodePath
							+ "/" + relative;
			} else {
				CatalogNode catalogNode = (CatalogNode) o;
				if (catalogNode == null) {
					return null;
				}
				String storageURL = catalogNode.getStorage().getUrl();
				if (!storageURL.endsWith("#")) {
					storageURL += "#";
				}
				parentDir = storageURL + catalogNode.getPath();
				if (!parentDir.endsWith("/")) {
					parentDir += "/";
				}
				
				String fileNodePath = URIUtil.encode(catalogNode.getPath(),
							org.apache.commons.httpclient.URI.allowed_fragment);
				displayed = catalogNode.getStorage().getName() + "/" + fileNodePath
							+ "/" + relative;
			}

			result.getTarget().setParentDirAddress(parentDir);
			result.getTarget().setRelativePath(relative);
			result.getTarget().setDisplayedString(displayed);
			result.getTarget().setUsingWildcards(false);
			result.getTarget().setProtocol(
					U6ProtocolConstants.UNICORE_SMS_PROTOCOL);
			return result;
		} catch (Exception e) {
			GPEActivator.log(IStatus.WARNING,
					"Could not apply value to table entry", e);
			return file;
		} finally {
			//serviceSelectionDialog.disposeNodes();
		}
	}

	@Override
	protected void updateContents(Object value) {
		if (defaultLabel == null) {
			return;
		}

		String text = "";
		if (value != null) {
			text = ((IFileParameterValue) getValue()).getSource()
					.getDisplayedString();
		}
		defaultLabel.setText(text);
	}

}
